package com.freesky.provider.order.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.freesky.common.dao.entity.Address;
import com.freesky.common.exception.EMallException;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.provider.order.service.IAddressService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author Freesky
 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Override
    public JSONResponse getAddressList(Long userId) {
        List<Address> list = new Address().selectList(new EntityWrapper().eq("user_id", userId));
        if(list==null){
            throw new EMallException("获取默认地址列表失败");
        }

        for(int i=0;i<list.size();i++){
            if(list.get(i).getDefaultAddress()){
                Collections.swap(list,0,i);
                break;
            }
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(list);
    }

    @Override
    public JSONResponse getAddress(Long addressId) {
        Address address = new Address();
        address.setAddressId(addressId);
        address = address.selectById();
        if(address==null){
            throw new EMallException("通过id获取地址失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(address);

    }

    @Override
    public JSONResponse addAddress(Address address) {
        //设置唯一默认
        setOneDefault(address);
        boolean insert = address.insert();
        if(!insert){
            throw new EMallException("添加地址失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse updateAddress(Address address) {

        //设置唯一默认
        setOneDefault(address);
        boolean update = address.updateById();
        if(! update){
            throw new EMallException("更新地址失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public void delAddress(Address address) {
        boolean delete = address.deleteById();
        if(!delete){
            throw new EMallException("删除地址失败");
        }
    }

    public void setOneDefault(Address address){
        //设置唯一默认
        if(address.getDefaultAddress()){
            List<Address> list = new Address().selectList(new EntityWrapper().eq("user_id", address.getAddressId()));
            for(Address a:list){
                a.setDefaultAddress(false);
                a.updateById();
            }
        }
    }
}
